﻿using Microsoft.Win32;
using movie.tool.library.hash;
using movie.tool.library.ui;
using movie.tool.module.film.model;
using movie.tool.module.film.service;
using movie.tool.module.http;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Net.Http.Json;
using System.Windows;
using System.Linq;
using System.Collections.Generic;

namespace movie.tool.module.film.ui
{
    /// <summary>
    /// PlayRoleInfoControl.xaml 的交互逻辑
    /// </summary>
    public partial class PlayRoleBookControl : BaseControl
    {
        public static readonly DependencyProperty ConfigProperty = DependencyProperty.Register("Config", typeof(MovieProject), typeof(PlayRoleBookControl));
        public MovieProject Config
        {
            get => (MovieProject)GetValue(ConfigProperty);
            set => SetValue(ConfigProperty, value);
        }
        public static readonly DependencyProperty BusyInfoProperty = DependencyProperty.Register("BusyInfo", typeof(BusyInfo), typeof(PlayRoleBookControl));
        public BusyInfo BusyInfo
        {
            get => (BusyInfo)GetValue(BusyInfoProperty);
            set => SetValue(BusyInfoProperty, value);
        }
        private BookChapter currentChapter;
        public BookChapter CurrentChapter
        {
            get => currentChapter;
            set
            {
                if(currentChapter != null)
                {
                    currentChapter.PropertyChanged -= CurrentChapterPropertyChanged;
                }
                currentChapter = value;
                if(currentChapter != null)
                {
                    currentChapter.PropertyChanged += CurrentChapterPropertyChanged;
                }
                SendPropertyChanged(nameof(CurrentChapter));
                UpdateBook();
            }
        }
        private void CurrentChapterPropertyChanged(object? sender, PropertyChangedEventArgs e)
        {
            if (CurrentChapter != null && object.Equals(e.PropertyName, nameof(CurrentChapter.Sequence)))
            {
                Config.ResortChapter();
            }
        }

        private PlayerRoleConfig currentRole;
        public PlayerRoleConfig CurrentRole
        {
            get => currentRole;
            set
            {
                currentRole = value;
                SendPropertyChanged(nameof(CurrentRole));
                UpdateBook();
            }
        }
        private PlayRoleBookConfig currentBook;
        public PlayRoleBookConfig CurrentBook
        {
            get => currentBook;
            set
            {
                currentBook = value;
                SendPropertyChanged(nameof(CurrentBook));
            }
        }
        /// <summary>
        /// 添加、删除和保存的按钮是否可见
        /// </summary>
        public Visibility ModifyVisible
        {
            get
            {
                if (Config != null && Config.ImportProject)
                {
                    return Visibility.Collapsed;
                }
                return Visibility.Visible;
            }
        }
        public Thickness PlayRoleListMargin
        {
            get
            {
                if (Config != null && Config.ImportProject)
                {
                    return new Thickness();
                }
                return new Thickness(0,33,0,0);
            }
        }
        public PlayRoleBookControl()
        {
            InitializeComponent();
        }
        private void UpdateBook()
        {
            if(CurrentChapter == null || CurrentRole == null)
            {
                CurrentBook = null;
            }
            else
            {
                if(currentRole.Id > 0 && currentChapter.Id > 0)
                {
                    CurrentBook = Config.FindBook(CurrentRole.Id, CurrentChapter.Id);
                }
                if(CurrentBook == null)
                {
                    CurrentBook = Config.FindBook(CurrentRole.Name, CurrentChapter.Name);
                }
                
            }
        }
        
        private async void AddChapterClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                if (Config.Chapters == null)
                {
                    Config.Chapters = new ObservableCollection<BookChapter>();
                }
                BookChapter param = new BookChapter();
                param.Name = "新建章节";
                param.Sequence = Config.Chapters.Count > 0 ? Config.Chapters[Config.Chapters.Count - 1].Sequence + 1 : 1;
                long? id = await MovieClient.SaveChapter(param, Config.Id);
                if (id != null && id > 0)
                {
                    param.Id = (long)id;
                    CurrentChapter = param;
                    Config.Chapters.Add(param);
                    MovieService.SaveProjectMovie(Config);
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void DeleteChapterClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                if (CurrentChapter == null)
                {
                    MessageBox.Show("请选择章节");
                    return;
                }
                MessageBoxResult result = MessageBox.Show("将删除所有角色的" + CurrentChapter.Name + "配置,是否确定删除?");
                if(result != MessageBoxResult.OK)
                {
                    return;
                }
                bool ret = await HttpInvoker.DeleteAsync("movieserver/chapters/" + CurrentChapter.Id);
                if (ret)
                {
                    Config.Chapters.Remove(CurrentChapter);
                    CurrentChapter = null;
                    MovieService.SaveProjectMovie(Config);
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }
        private void BookFileBrowserClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            if (CurrentChapter == null)
            {
                MessageBox.Show("请选择一个章节再操作");
                return;
            }
            if (CurrentRole == null)
            {
                MessageBox.Show("请选择一个角色再操作");
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                OpenFileDialog dialog = new OpenFileDialog();
                //选择文件
                dialog.Filter = "word文档(*.doc,*.docx,*.wps)|*.doc;*.docx;*.wps";
                dialog.Title = "选择电子书文件";

                if (CurrentBook == null)
                {
                    CurrentBook = new PlayRoleBookConfig();
                    CurrentBook.PlayRoleId = CurrentRole.Id;
                    currentBook.ChapterId = CurrentChapter.Id;
                    if (Config.Books == null)
                    {
                        Config.Books = new ObservableCollection<PlayRoleBookConfig>();
                    }
                    Config.Books.Add(CurrentBook);
                }

                if (!string.IsNullOrEmpty(CurrentBook.FilePath))
                {
                    string filePath = Path.Join(MovieService.ProjectJsonFilePath(Config.Id), CurrentBook.FilePath);
                    dialog.InitialDirectory = Path.GetDirectoryName(filePath);
                }

                bool? result = dialog.ShowDialog();
                if (result != null && result == true)
                {
                    string chapterName = CurrentChapter.Name;
                    if ("新建章节".Equals(chapterName))
                    {
                        string name = Path.GetFileNameWithoutExtension(dialog.FileName);
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            chapterName = name;
                        }
                    }
                    string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                    if (dialog.FileName.StartsWith(rootPath))
                    {
                        //选择的文件在项目目录下,那就不用复制了
                        CurrentBook.FilePath = Path.GetRelativePath(rootPath, dialog.FileName);
                    }
                    else
                    {
                        string path = Path.Combine(rootPath, "books", chapterName);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        path = Path.Combine(path, Path.GetFileName(dialog.FileName));
                        if (File.Exists(path))
                        {
                            string selectDigest = SHA1Hash.FileDigest(dialog.FileName);
                            string targetDigest = SHA1Hash.FileDigest(path);
                            if (!selectDigest.Equals(targetDigest))
                            {
                                MessageBox.Show("文件" + path + "已经存在,无法复制,请选择不同名称的文件");
                                return;
                            }
                            else
                            {
                                //相同,不需要复制
                                CurrentBook.FilePath = Path.GetRelativePath(rootPath, path);
                            }
                        }
                        else
                        {
                            File.Copy(dialog.FileName, path);
                            CurrentBook.FilePath = Path.GetRelativePath(rootPath, path);
                        }
                    }
                    CurrentChapter.Name = chapterName;
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void PlayRoleBookSubmitClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                if (CurrentChapter == null)
                {
                    MessageBox.Show("请选择一个章节再操作");
                    return;
                }
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                bool ret = await MovieClient.UpdateChapter(CurrentChapter);
                if (ret)
                {
                    //查看文件是否修改
                    if (CurrentBook != null && !string.IsNullOrEmpty(CurrentBook.FilePath))
                    {
                        string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                        string filePath = Path.Join(rootPath, CurrentBook.FilePath);

                        if (File.Exists(filePath))
                        {
                            if (!await MovieClient.BookFileEquals(filePath,currentBook.Id))
                            {
                                //文件不一样,那上传文件
                                long? res = await MovieClient.UploadBookFile(filePath, CurrentRole.Id, CurrentChapter.Id, CurrentBook.FilePath);
                                if (res != null)
                                {
                                    CurrentBook.Id = (long)res;
                                    MessageBox.Show("提交成功");
                                }
                                else
                                {
                                    MessageBox.Show("章节信息保存成功,文件上传失败");
                                }
                            }
                            else
                            {
                                MessageBox.Show("提交成功");
                            }
                        }
                        else
                        {
                            MessageBox.Show("提交成功");
                        }
                    }
                    else
                    {
                        MessageBox.Show("提交成功");
                    }
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private void BaseControl_Loaded(object sender, RoutedEventArgs e)
        {
            SendPropertyChanged(nameof(ModifyVisible));
            SendPropertyChanged(nameof(PlayRoleListMargin));
        }

        private async void BookFileDownloadClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy || CurrentBook == null)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.BusyMessage = "下载中...";
                string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                await MovieSynchronizer.SyncPlayRoleBook(rootPath, CurrentBook);
            }
            finally
            {
                BusyInfo.Reset();
            }
        }
    }
}
